package com.zhentao.filter;

import com.zhentao.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Configuration
public class WeMediaLoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断是否是登录操作 如果是登录直接放行
        String path = request.getURI().getPath();
        if(path.contains("/login")){
            return chain.filter(exchange);
        }

        //判断token是否正确
        String token = request.getHeaders().getFirst("token");
        if(token == null){
            //token 不存在
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //token存在 但token有可能是假的  或者过期
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //验证token是否过期
            int result = AppJwtUtil.verifyToken(claims);
            if(result == 1 || result == 2){
                //token过期了
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //我们有很多个微服务  原先都是将userid存到 Threadlocal  Threadlocal保证不了是隔离的
            //通过header放入每个服务里面
            //使用时在取出
            //如果token 是正确的  执行操作的时候需要用到userId  -token
            Object userId = claims.get("id");
            //headers 里面 的每一个 header  添加 一个 userId
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();
            //重置header  放回去
            exchange.mutate().request(serverHttpRequest).build();

        } catch (Exception e) {
            //token是错误的
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
















